package vooga.behaviors;

import java.util.HashSet;
import java.util.Set;

import vooga.core.AbstractLevel;
import vooga.entities.Entity;


/**
 * Calls a level's handleCollision method upon collision
 * @author congyiwu
 *
 */
public class OnCollideBehavior extends AbstractBehavior
{
    private Set<Entity> myObstacles;
    //store obstacles to add or remove until next step so we don't get
    //concurrent modification exceptions
    private Set<Entity> myObstaclesToAdd;
    private Set<Entity> myObstaclesToRemove;
    private AbstractLevel myController;

    public OnCollideBehavior (Iterable<Entity> obstacles, AbstractLevel controller)
    {
        myObstacles = new HashSet<Entity>();
        for(Entity a : obstacles)
        	myObstacles.add(a);
        
        myObstaclesToAdd = new HashSet<Entity>();
        myObstaclesToRemove = new HashSet<Entity>();
        
        myController = controller;
    }

    public void step (Entity target)
    {
       	for(Entity e : myObstaclesToAdd)
    		myObstacles.add(e);
       	myObstaclesToAdd.clear();

       	for(Entity e : myObstaclesToRemove)
        	myObstacles.remove(e);
       	myObstaclesToRemove.clear();
       	
    	for(Entity e : myObstacles)
        	if(target.intersects(e))
        		myController.handleCollision(target, e);
    }

    public void addObstacle(Entity a)
    {
    	myObstaclesToAdd.add(a);
    }
    
    public boolean removeObstacle(Entity a)
    {
    	return myObstaclesToRemove.add(a);
    }
}
